package cate.game.activity.battleroyale.po;

import cate.common.table.activity.battleroyale.row.BattleRoyaleBaseRow;
import cate.common.table.activity.battleroyale.row.BattleRoyaleChapterRow;
import cate.common.table.activity.battleroyale.row.BattleRoyaleLevelRow;
import cate.common.table.d.*;
import cate.game.activity.base.core.RoleFarmActivitySingle;
import cate.game.activity.battleroyale.BattleRoyaleFTC;
import cate.game.activity.battleroyale.BattleRoyaleHandler;
import cate.game.activity.battleroyale.msg.BattleRoyaleDataResp;
import cate.game.activity.battleroyale.msg.BattleRoyaleLevelDataResp;
import cate.game.activity.battleroyale.msg.BattleRoyaleRecordResp;
import cate.game.chat.ChatContentParam;
import cate.game.mail.po.MailBuilder;
import cate.game.play.part.FightSide;
import cate.game.play.part.PlaySide;
import cate.game.play.proce.play.PlayPO;
import cate.game.res.MixRes;
import cate.game.role.Role;
import cate.game.role.mail.Mail;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@NoteClass("玩家单个庙街食神记活动数据")
public class RoleBattleRoyale extends RoleFarmActivitySingle {
    @NoteField("下次刷新时间")
    public long nextRefreshTime;

    @NoteField(value = "章节数")
    public int chapter;

    @NoteField(value = "关卡")
    public List<BattleRoyaleLevel> levels;

    @NoteField(value = "是否完成")
    public boolean over;

//	@NoteField(value = "强制开启")
//	public boolean forceOpen;

    public RoleBattleRoyale() {

    }

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (levels == null) {
            levels = new ArrayList<>();
        }
    }

    private boolean canPreUnlock() {
        return getNextLevelRow() == null && levels.stream().allMatch(e -> e.rewardGot);
    }

    @JsonIgnore
    public BattleRoyaleBaseRow getRow() {
        return getRole().getGame().table.battleRoyale.base.get(base.configTid);
    }

//    public synchronized EcResult<Void> payUnlock() {
//        EcResult<Void> r = new EcResult<>();
//        if (!enable()) {
//            return r.fail("活动已结束");
//        }
//        if (!canPreUnlock()) {
//            return r.fail("领取所有关卡奖励后才能解锁下一章节");
//        }
//        BattleRoyaleChapterRow chapterRow = role.getGame().table.battleRoyale.chapter.getChapterRow(getRow().group, this.chapter);
//        if (StringUtils.isNotBlank(chapterRow.unlockConsumeStr)) {
//            EcResult<MixResItem> consumeRes = new MixRes(chapterRow.unlockConsumeStr)
//                    .consume(role, null);
//            if (!consumeRes.ok()) {
//                role.getGame().notice.tipResItem(role, consumeRes.data);
//                return r.fail(consumeRes.message);
//            }
//        }
//        unlockNextChapter();
//        return r;
//    }

    private void lampPassChapter(int chapter, String rewardStr) {
        List<ChatContentParam> params = new ArrayList<>();
        params.add(ChatContentParam.c(role.getBase().name));
        params.add(ChatContentParam.c(chapter));
        params.add(ChatContentParam.c(ChatContentParam.TYPE_MIX_RES, new MixRes(rewardStr)));
        role.getGame().notice.lampOnline(role, GDNotice.TextId.BATTLE_ROYALE_PASS_CHAPTER, params);
    }

    /**
     * 挑战副本
     */
    public synchronized EcResult<Void> challenge(int chapter, int level) {
        EcResult<Void> r = new EcResult<>();
        if (!enable()) {
            return r.fail("活动已结束");
        }
        if (isFighting()) {
            return r.fail("当前战斗未结束");
        }
        if (this.chapter != chapter) {
            return r.fail("章节已过期，请关闭进入下一章节");
        }
        BattleRoyaleLevelRow levelRow = getLevelRow(chapter, level);
        if (levelRow == null) {
            return r.fail("所选关卡不存在");
        }
        BattleRoyaleLevel levelObj = getLevelObj(level);
        if (levelObj == null) {
            return r.fail("请先挑战前面的关卡");
        }
        if (levelObj.passed) {
            return r.fail("所选关卡已通过");
        }
        r = doChallenge(chapter, level, GDPosition.DEFAULT_POS_NUM);
        if (r.ok()) {
            levelObj.first = false;
            noticeLevel(levelObj);
        }
        return r;
    }

    public EcResult<Void> doChallenge(int chapter, int level, byte posNum) {
        EcResult<Void> r = new EcResult<>();
        BattleRoyaleLevelRow tpl = getLevelRow(chapter, level);
        if (tpl == null) {
            return r.fail("所选关卡不存在");
        }
        BattleRoyaleChapterRow chapterRow = role.getGame().table.battleRoyale.chapter.getChapterRow(getRow().group, this.chapter);
        if (chapterRow == null) {
            return r.fail("章节不存在");
        }
//		List<FbGainRow> gains = new ArrayList<>();
//		if (!XT.isBlank(chapterRow.blessIds)) {
//			for (Integer blessId : chapterRow.blessIds) {
//				BattleRoyaleBlessRow blessRow = role.getGame().table.battleRoyale.bless.get(blessId);
//				if(blessRow!=null){
//					for (Integer gainId : blessRow.gainIds) {
//						FbGainRow gainRow = role.getGame().table.fbGain.base.get(gainId);
//						if(gainRow!=null){
//							gains.add(gainRow);
//						}
//					}
//				}
//			}
//		}
        EcResult<PlaySide> psA_r = role.getGame().fight.side.createPlaySideByRole(role, getFightFuncId(), GDPosition.DEFAULT_POS_NUM);
        if (!psA_r.ok()) {
            return r.fail(psA_r.message);
        }
        FightSide fsA = role.getGame().fight.side.createFightSideByPlaySide(GDFight.Team.A, psA_r.data);
        EcResult<FightSide> fsRes = role.getGame().fight.side.createFightSideByCode(GDFight.Team.B, tpl.getInsCode(posNum));
        if (!fsRes.ok()) {
            return r.fail(fsRes.message);
        }
        BattleRoyaleFTC context = new BattleRoyaleFTC(role, getFightFuncId(), tpl);
        context.funcId = getFightFuncId();
        context.playStory.level = tpl.id;
        EcResult<PlayPO> fightRes = role.getGame().play.startByRole(role, context, fsA, fsRes.data);
        if (!fightRes.ok()) {
            return r.fail(fightRes.message);
        }
        this.startFighting();
        return r;
    }

    @JsonIgnore
    public synchronized EcResult<Void> getReward(int chapter, int level) {
        EcResult<Void> r = new EcResult<>();
        if (!enable()) {
            return r.fail("活动已结束");
        }
        if (this.chapter != chapter) {
            return r.fail("章节已过期，请进入下一章节");
        }
        BattleRoyaleLevel levelObj = getLevelObj(level);
        if (levelObj == null) {
            return r.fail("所选关卡不存在");
        }
        if (levelObj.rewardGot) {
            return r.fail("所选关卡奖励已领取");
        }
        if (!levelObj.passed) {
            return r.fail("所选关卡未通关，无法领奖");
        }
        BattleRoyaleLevelRow levelRow = getLevelRow(chapter, level);
        if (levelRow == null) {
            return r.fail("所选关卡不存在");
        }
        levelObj.rewardGot = true;
        MixRes reward = new MixRes(levelRow.rewardStr);
        reward.add(role, true, GDOperation.BATTLE_ROYALE_REWARD, chapter);
        role.getGame().notice.dialogReward(role, reward);
        noticeLevel(levelObj);
        BattleRoyaleLevelRow nextRow = getNextLevelRow(level);
        if (nextRow == null) {
            lampPassChapter(chapter, levelRow.rewardStr);
        }
//        if (isLastCharpterOver()) {
        if (allLevelOver()) {
            unlockNextChapter();
        }
        return r;
    }

//	/**
//	 * 开启牛逼模式
//	 */
//	private PlaySide createNiubiModePs(BattleRoyaleLevelRow levelRow){
//		Position position = role.getFight().getPosition(funcId());
//		if (position == null) {
//			return null;
//		}
//		List<Integer> newBiTypes = null;
//		PlaySide ps = new PlaySide();
//		ps.snapshot = new RoleSnapshot(role);
//		for (HeroGrid grid : position.grids) {
//			Hero hero = role.getBag().hero.getItem(grid.uid);
//			if (hero != null) {
//				Hero newbiHero = createNewBiHero(newBiTypes, hero);
//				BattleHero bh = role.getGame().fight.hero.build(new PowerFactor(role, ps), newbiHero, grid.pos);
//				if (bh != null) {
//					bh.pos = grid.pos;
//					bh.origin = grid.origin;
//					ps.addHero(bh);
//				}
//			}
//		}
//		return ps;
//	}
//
//	private Hero createNewBiHero(List<Integer> newBiTypes, Hero oldHero){
//		Hero newHero = oldHero.copy();
//		for (Integer type : newBiTypes) {
//
//		}
//		return newHero;
//	}

    @JsonIgnore
    public synchronized EcResult<Void> fastGetReward(int chapter) {
        EcResult<Void> r = new EcResult<>();
        if (!enable()) {
            return r.fail("活动已结束");
        }
        if (this.chapter != chapter) {
            return r.fail("章节已过期，请进入下一章节");
        }
        MixRes reward = new MixRes();
        for (BattleRoyaleLevel levelObj : levels) {
            if (levelObj.rewardGot) {
                continue;
            }
            if (!levelObj.passed) {
                continue;
            }
            BattleRoyaleLevelRow levelRow = getLevelRow(chapter, levelObj.level);
            if (levelRow == null) {
                continue;
            }
            levelObj.rewardGot = true;
            reward.addList(new MixRes(levelRow.rewardStr));
            if (getNextLevelRow(levelObj.level) == null) {
                lampPassChapter(chapter, levelRow.rewardStr);
            }
        }
        if (reward.isEmpty()) {
            return r.fail("没有奖励可以领取");
        }
        reward.add(role, true, GDOperation.BATTLE_ROYALE_REWARD, chapter);
        role.getGame().notice.dialogReward(role, reward);
        noticeUpdate();
//        if (isLastCharpterOver()) {
        if (allLevelOver()) {
            unlockNextChapter();
        }
        return r;
    }

    @JsonIgnore
    private boolean allLevelOver() {
        BattleRoyaleLevelRow nextRow = getNextLevelRow();
        return nextRow == null && levels.stream().allMatch(e -> e.rewardGot);
    }

    public EcResult<Void> getRecord(int chapter, int level) {
        EcResult<Void> r = new EcResult<>();
        if (!enable()) {
            return r.fail("活动已结束");
        }
        BattleRoyaleHandler handler = role.getGame().activityGlobal.getHandler(funcId());
        if (handler == null) {
            return r.fail("活动已结束");
        }
        BattleRoyaleLevelRow levelRow = getLevelRow(chapter, level);
        if (levelRow == null) {
            return r.fail("所选关卡不存在");
        }
        BattleRoyaleRecord record = handler.getRecord(base.activityId, chapter, level);
        role.sendNow(new BattleRoyaleRecordResp(funcId(), record));
        return r;
    }

    public synchronized void onPass(int chapter, int level) {
        BattleRoyaleLevel levelObj;
        if (this.chapter == chapter && (levelObj = getLevelObj(level)) != null && !levelObj.passed) {
            levelObj.passed = true;
            BattleRoyaleLevelRow nextRow = getNextLevelRow(level);
            if (nextRow != null) {
                unlockNextLevel(false, false);
            }
        }
    }

    private BattleRoyaleLevelRow getLevelRow(int chapter, int level) {
        return role.getGame().table.battleRoyale.level.getLevelRow(getRow().group, chapter, level);
    }

    private BattleRoyaleLevelRow getNextLevelRow() {
        return getNextLevelRow(levels.size());
    }

    private BattleRoyaleLevelRow getNextLevelRow(int level) {
        return getLevelRow(chapter, level + 1);
    }

    /**
     * 解锁下一等级
     */
    private synchronized void unlockNextLevel(boolean notice, boolean expire) {
        BattleRoyaleLevelRow row = getNextLevelRow();
        if (row == null) {
            unlockNextChapter();
            return;
        }
        BattleRoyaleLevel nextLevel = new BattleRoyaleLevel();
        nextLevel.level = levels.size() + 1;
        nextLevel.first = true;
        logger.info("{}解锁庙街食神记funcId={},activityId={},chapter={},level={},下次刷新时间={}", role.getBase().name, funcId(), base.activityId, chapter, nextLevel.level, new java.util.Date(nextRefreshTime));
        this.levels.add(nextLevel);
        if (notice) {
            noticeUpdate(expire);
        }
    }

    private BattleRoyaleLevel getLevelObj(int level) {
        return levels.stream().filter(e -> e.level == level).findAny().orElse(null);
    }

    private void sendMailBeforeChapterOver() {
        if (CollectionUtils.isNotEmpty(levels)) {
            List<BattleRoyaleLevel> unRewardList = levels.stream().filter(e -> e.passed && !e.rewardGot).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(unRewardList)) {
                MixRes reward = new MixRes();
                for (BattleRoyaleLevel level : unRewardList) {
                    BattleRoyaleLevelRow levelRow = getLevelRow(chapter, level.level);
                    if (levelRow != null) {
                        reward.addList(new MixRes(levelRow.rewardStr));
                    }
                }
                if (!reward.isEmpty()) {
                    Mail mail = new MailBuilder()
                            .setContentId(GDMail.Tid.BATTLE_ROYALE_MAIL)
                            .setReward(reward)
                            .setOperation(GDOperation.BATTLE_ROYALE_MAIL_REWARD)
                            .setOperationSub(chapter)
                            .build();
                    role.getGame().mail.send(role, mail);
                }
            }
        }
    }

    /**
     * 解锁下一章节
     */
    private synchronized void unlockNextChapter() {
        unlockNextChapter(false);
    }

    /**
     * 解锁下一章节
     */
    private synchronized void unlockNextChapter(boolean expire) {
        sendMailBeforeChapterOver();
        BattleRoyaleChapterRow chapterRow = role.getGame().table.battleRoyale.chapter.getChapterRow(getRow().group, chapter + 1);
        if (chapterRow == null) {
            over = true;
//            if (game().time.now() < nextRefreshTime) {
//                //如果提前结束，预留
//            }
            preClear();
            forceNotice();
            //提前打完
            return;
        }
        nextRefreshTime += chapterRow.expireSeconds * 1000L;
        chapter++;
        levels.clear();
        unlockNextLevel(nextRefreshTime >= game().time.now(), expire);
    }

    @Override
    public void excelCheck() {

    }

    private void preClear() {
        logger.info("{}的庙街食神记结束", role.getBase().name);
        nextRefreshTime = 0;
        chapter = 0;
        levels.clear();
        role.getGame().fight.position.clearPosition(role, getFightFuncId());
    }

    @Override
    public boolean enable() {
        return super.enable() && !over && limitCheck();
    }

    @Override
    public void onRoleOpen() {

    }

    @Override
    public void onRoleEnd() {
        sendMailBeforeChapterOver();
        preClear();
        fighting = false;
        over = false;
    }

    @Override
    public void initSend() {
        noticeUpdate();
    }

//	private boolean dependOnOther(){
//		BattleRoyaleBaseRow baseRow = getRow();
//		if (baseRow != null && baseRow.dependOnActivityId > 0 && !forceOpen) {
//			BattleRoyaleBaseRow dependActivityRow = role.getGame().table.battleRoyale.base.get(baseRow.dependOnActivityId);
//			if(dependActivityRow != null){
//				RoleBattleRoyale battleRoyale = role.getActivity().battleRoyale.getActivity(dependActivityRow.funcId);
//				return battleRoyale != null && battleRoyale.base != null && battleRoyale.base.activityId == baseRow.dependOnActivityId && battleRoyale.over;
//			}
//		}
//		return true;
//	}

    private boolean limitCheck() {
        return role.getGame().table.common.funcEnable.get(getFightFuncId()) == null || role.getGame().table.common.funcEnable.isEnable(
                role.getBase().level,
                role.getBase().vip,
                0,
                0,
                getFightFuncId(),
                role.getFarm().adventure.getAdventurePassedNum()
        ).ok();
    }

    //不能走onstart
    private void start() {
        if (nextRefreshTime == 0) {
            over = false;
            nextRefreshTime = game().time.now();
            unlockNextChapter();
        }
    }

    public synchronized void tick() {
        if (!enable()) {
            return;
        }
        if (nextRefreshTime == 0) {
            start();
        }
        if (nextRefreshTime == 0 || nextRefreshTime > game().time.now()) {
            return;
        }
        if (super.isFighting()) {
            role.getGame().fight.task.handleResultForce(role, getFightFuncId(), true);
        }
        while (enable() && nextRefreshTime != 0 && nextRefreshTime <= game().time.now()) {
            unlockNextChapter(true);
        }
    }

    public void noticeUpdate() {
        if (enable()) {
            role.sendNow(new BattleRoyaleDataResp(this, false));
        }
    }

    public void noticeUpdate(boolean expire) {
        if (enable()) {
            role.sendNow(new BattleRoyaleDataResp(this, expire));
        }
    }

    public void forceNotice() {
        role.sendNow(new BattleRoyaleDataResp(this, false));
    }

    public void noticeLevel(BattleRoyaleLevel level) {
        if (enable()) {
            role.sendNow(new BattleRoyaleLevelDataResp(funcId(), level));
        }
    }

    @Override
    public int getFightFuncId() {
        return base.funcId;
    }

    public void GMReset() {
        over = false;
        onRoleEnd();
    }

    public void GMSetChapter(int chapter) {
        BattleRoyaleBaseRow row = getRow();
        if (row == null) {
            return;
        }
        BattleRoyaleChapterRow chapterRow = role.getGame().table.battleRoyale.chapter.getChapterRow(row.group, chapter);
        if (chapterRow != null) {
            this.chapter = chapter;
            this.levels.clear();
            unlockNextLevel(true, false);
            noticeUpdate();
        }
    }
}
